# -*- coding: utf-8 -*-
"""
This module provides a collection of concurrency related
object generators. These generators will create either
native threading based or greenlet based objects depending
on which threading_model is selected.
"""
import asyncio

__license__ = 'http://mozilla.org/MPL/2.0/'


class Promise(object):
    """
    封装 event
    """

    def __init__(self, event):
        object.__setattr__(self, '_event', event)
        object.__setattr__(self, '_value', None)

    def __getattr__(self, name):
        return getattr(self._event, name)

    def __setattr__(self, name, value):
        if hasattr(self._event, name):
            object.__setattr__(self._event, name, value)
        else:
            object.__setattr__(self, name, value)

    @property
    def value(self):
        return self._value

    def set(self, value):
        object.__setattr__(self, '_value', value)
        self._event.set()

    async def wait(self, timeout=None):
        await asyncio.wait_for(self._event.wait(), timeout=timeout)  # 实现timeout
        if not await self._event.wait():
            raise RuntimeError(
                u'Promise timeout after %.02f seconds.' % timeout)
        return self._value


def _new_asyncio_event():
    from asyncio import Event
    return Event()


def new_promise():
    return Promise(_new_asyncio_event())
